package com.example.controller;

import com.alibaba.fastjson2.JSON;
import com.example.entity.User;
import com.example.entity.UserPage;
import com.example.service.UserService;
import com.github.pagehelper.Page;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author:0xOO
 * @Date: 2018/9/26 0026
 * @Time: 14:42
 */
@CrossOrigin
@RestController
@RequestMapping("/testBoot")
public class UserController {
    @Autowired
    private UserService userService;
    static Integer count = 0;
    /**
     * 根据id返回与之对应的对象
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "testFailure")
    @GetMapping("getUser/{id}")
    @ApiOperation(notes = "通过id获取一个用户", value = "get user info")
    public ResponseEntity<User> GetUser(@PathVariable Integer id){
        if(count>10){
            throw new RuntimeException("系统异常");
        }
        User user = userService.selectById(id);
        count++;
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    public ResponseEntity<User> testFailure(Integer id){
        System.out.println("testFailure");
        return new ResponseEntity<>(new User(),HttpStatus.OK);
    }

    /**
     * 获取用户列表
     * @return
     */
    @RequestMapping("getUserList")
    public ResponseEntity<List<User>>  getUserList()  {
        List<User> userList = userService.getUserList();
        return new ResponseEntity<>(userList, HttpStatus.OK);
    }
    /**
     * 一次插入一个用户
     * @param param
     * @return
     */
    @PostMapping("/insertUser")
    public ResponseEntity insertUser(@RequestBody String param)  {
        User user1 = JSON.toJavaObject(JSON.parseObject(param), User.class);
        new Thread(()->{userService.insert(user1);}).start();
        return ResponseEntity.ok().build();
    }

    /**
     * 批量进行插入
     * @return
     */
    @PostMapping("/insertBatch")
    public ResponseEntity<Void> insertBatch(){
        new Thread(()->{userService.insertBatch(User.getListUser());}).start();
        return ResponseEntity.ok().build();
    }

    @PostMapping ("/findByPage")
    public ResponseEntity<UserPage> findByPage(Integer pageNo,Integer pageSize){
        Long start =  System.nanoTime();
        Page<User> serviceResult=  userService.findByPage(pageNo,pageSize);
        UserPage userPage = new UserPage();
        userPage.setPageNum(pageNo);
        userPage.setPageSize(pageSize);
        userPage.setTotal(serviceResult.getTotal());
        userPage.setList(serviceResult);
        System.out.println("查询耗时："+(System.nanoTime()-start));
        return new ResponseEntity<>(userPage, HttpStatus.OK);
    }

}
